<template>
  <div class="jsa-list">
    <div class="page-container">
      <div class="page-header">
        <h2>JSA管理</h2>
        <div class="header-actions">
          <el-button type="primary" @click="goToCreate">
            <el-icon><Plus /></el-icon>
            创建JSA
          </el-button>
          <el-button @click="refreshList">
            <el-icon><Refresh /></el-icon>
            刷新
          </el-button>
        </div>
      </div>
      
      <!-- 标签页 -->
      <el-tabs v-model="activeTab" @tab-change="handleTabChange">
        <el-tab-pane label="JSA列表" name="list">
          <div class="tab-content">
      
            <!-- 筛选条件 -->
            <el-card class="filter-card">
              <el-form :model="searchForm" inline>
                <el-form-item label="JSA状态">
                  <el-select v-model="searchForm.status" placeholder="全部状态" clearable>
                    <el-option label="全部" value="" />
                    <el-option label="草稿" value="draft" />
                    <el-option label="待确认" value="pending" />
                    <el-option label="已确认" value="confirmed" />
                    <el-option label="已过期" value="expired" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="作业类型">
                  <el-select v-model="searchForm.workType" placeholder="全部类型" clearable>
                    <el-option label="全部" value="" />
                    <el-option label="高空作业" value="high_altitude" />
                    <el-option label="动火作业" value="hot_work" />
                    <el-option label="电气作业" value="electrical" />
                    <el-option label="受限空间" value="confined_space" />
                    <el-option label="起重作业" value="lifting" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="创建时间">
                  <el-date-picker
                    v-model="searchForm.dateRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="handleSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="handleReset">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
      
            <!-- JSA列表 -->
            <el-card>
              <el-table
                v-loading="loading"
                :data="tableData"
                stripe
                border
              >
                <el-table-column prop="jsaNumber" label="JSA编号" width="150" />
                <el-table-column prop="permitNumber" label="关联许可证" width="150" />
                <el-table-column prop="workType" label="作业类型" width="120">
                  <template #default="{ row }">
                    <el-tag :type="getWorkTypeTagType(row.workType)">
                      {{ getWorkTypeLabel(row.workType) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="location" label="作业地点" width="200" />
                <el-table-column prop="status" label="状态" width="100">
                  <template #default="{ row }">
                    <el-tag :type="getStatusTagType(row.status)">
                      {{ getStatusLabel(row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="confirmProgress" label="确认进度" width="120">
                  <template #default="{ row }">
                    <el-progress 
                      :percentage="row.confirmProgress" 
                      :status="getProgressStatus(row.confirmProgress)"
                      :stroke-width="6"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="creator" label="创建人" width="100" />
                <el-table-column prop="createTime" label="创建时间" width="160" />
                <el-table-column prop="confirmDeadline" label="确认截止时间" width="160" />
                <el-table-column label="操作" width="280" fixed="right">
                  <template #default="{ row }">
                    <el-button type="primary" size="small" @click="handleView(row)">
                      查看
                    </el-button>
                    <el-button 
                      v-if="canEdit(row.status)" 
                      type="warning" 
                      size="small" 
                      @click="handleEdit(row)"
                    >
                      编辑
                    </el-button>
                    <el-button 
                      v-if="canConfirm(row.status)" 
                      type="success" 
                      size="small" 
                      @click="handleConfirm(row)"
                    >
                      确认
                    </el-button>
                 
                    <el-button 
                      v-if="canDelete(row.status)" 
                      type="danger" 
                      size="small" 
                      @click="handleDelete(row)"
                    >
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 分页 -->
              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="pagination.page"
                  v-model:page-size="pagination.size"
                  :total="pagination.total"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                />
              </div>
            </el-card>
          </div>
        </el-tab-pane>
        
        <!-- 待确认JSA标签页 -->
        <el-tab-pane label="待确认JSA" name="confirm">
          <div class="tab-content">
            <!-- 待确认JSA筛选条件 -->
            <el-card class="filter-card">
              <el-form :model="confirmSearchForm" inline>
                <el-form-item label="作业类型">
                  <el-select v-model="confirmSearchForm.workType" placeholder="全部类型" clearable>
                    <el-option label="全部" value="" />
                    <el-option label="高空作业" value="high_altitude" />
                    <el-option label="动火作业" value="hot_work" />
                    <el-option label="电气作业" value="electrical" />
                    <el-option label="受限空间" value="confined_space" />
                    <el-option label="起重作业" value="lifting" />
                  </el-select>
                </el-form-item>
                
                <el-form-item label="确认截止时间">
                  <el-date-picker
                    v-model="confirmSearchForm.deadlineRange"
                    type="daterange"
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    format="YYYY-MM-DD"
                    value-format="YYYY-MM-DD"
                  />
                </el-form-item>
                
                <el-form-item>
                  <el-button type="primary" @click="handleConfirmSearch">
                    <el-icon><Search /></el-icon>
                    搜索
                  </el-button>
                  <el-button @click="handleConfirmReset">
                    <el-icon><Refresh /></el-icon>
                    重置
                  </el-button>
                </el-form-item>
              </el-form>
            </el-card>
            
            <!-- 待确认JSA列表 -->
            <el-card>
              <el-table
                v-loading="confirmLoading"
                :data="confirmTableData"
                stripe
                border
              >
                <el-table-column prop="jsaNumber" label="JSA编号" width="150" />
                <el-table-column prop="permitNumber" label="关联许可证" width="150" />
                <el-table-column prop="workType" label="作业类型" width="120">
                  <template #default="{ row }">
                    <el-tag :type="getWorkTypeTagType(row.workType)">
                      {{ getWorkTypeLabel(row.workType) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column prop="location" label="作业地点" width="200" />
                <el-table-column prop="confirmProgress" label="确认进度" width="120">
                  <template #default="{ row }">
                    <el-progress 
                      :percentage="row.confirmProgress" 
                      :status="getProgressStatus(row.confirmProgress)"
                      :stroke-width="6"
                    />
                  </template>
                </el-table-column>
                <el-table-column prop="creator" label="创建人" width="100" />
                <el-table-column prop="createTime" label="创建时间" width="160" />
                <el-table-column prop="confirmDeadline" label="确认截止时间" width="160">
                  <template #default="{ row }">
                    <span :class="{ 'deadline-urgent': isDeadlineUrgent(row.confirmDeadline) }">
                      {{ row.confirmDeadline }}
                    </span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="150" fixed="right">
                  <template #default="{ row }">
                    <el-button type="primary" size="small" @click="handleView(row)">
                      查看
                    </el-button>
                    <el-button type="success" size="small" @click="handleConfirm(row)">
                      确认
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
              
              <!-- 分页 -->
              <div class="pagination-container">
                <el-pagination
                  v-model:current-page="confirmPagination.page"
                  v-model:page-size="confirmPagination.size"
                  :total="confirmPagination.total"
                  :page-sizes="[10, 20, 50, 100]"
                  layout="total, sizes, prev, pager, next, jumper"
                  @size-change="handleConfirmSizeChange"
                  @current-change="handleConfirmCurrentChange"
                />
              </div>
            </el-card>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>
    
    <!-- JSA详情对话框 -->
    <JSADetailDialog 
      v-model="detailDialogVisible" 
      :jsa-data="selectedJSA" 
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import JSADetailDialog from './components/JSADetailDialog.vue'

const router = useRouter()

interface JSAItem {
  id: number
  jsaNumber: string
  permitNumber: string
  workType: string
  location: string
  status: string
  confirmProgress: number
  creator: string
  createTime: string
  confirmDeadline: string
}

const loading = ref(false)
const confirmLoading = ref(false)
const tableData = ref<JSAItem[]>([])
const confirmTableData = ref<JSAItem[]>([])
const activeTab = ref('list')
const detailDialogVisible = ref(false)
const selectedJSA = ref<any>(null)

const searchForm = reactive({
  status: '',
  workType: '',
  dateRange: []
})

const confirmSearchForm = reactive({
  workType: '',
  deadlineRange: []
})

const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

const confirmPagination = reactive({
  page: 1,
  size: 10,
  total: 0
})

// 模拟数据
const mockData: JSAItem[] = [
  {
    id: 1,
    jsaNumber: 'JSA20250115001',
    permitNumber: 'WP20250115001',
    workType: 'high_altitude',
    location: 'A区3楼外墙维修',
    status: 'confirmed',
    confirmProgress: 100,
    creator: '张三',
    createTime: '2025-01-15 14:30',
    confirmDeadline: '2025-01-16 18:00'
  },
  {
    id: 2,
    jsaNumber: 'JSA20250115002',
    permitNumber: 'WP20250115002',
    workType: 'hot_work',
    location: 'B区管道焊接',
    status: 'pending',
    confirmProgress: 60,
    creator: '李四',
    createTime: '2025-01-15 10:20',
    confirmDeadline: '2025-01-17 18:00'
  },
  {
    id: 3,
    jsaNumber: 'JSA20250115003',
    permitNumber: 'WP20250115003',
    workType: 'electrical',
    location: '配电室设备检修',
    status: 'draft',
    confirmProgress: 0,
    creator: '王五',
    createTime: '2025-01-15 09:15',
    confirmDeadline: '2025-01-18 18:00'
  },
  {
    id: 4,
    jsaNumber: 'JSA20250115004',
    permitNumber: 'WP20250115004',
    workType: 'confined_space',
    location: '储罐内部清洗',
    status: 'expired',
    confirmProgress: 40,
    creator: '赵六',
    createTime: '2025-01-15 16:45',
    confirmDeadline: '2025-01-16 18:00'
  }
]

// 获取JSA列表
const fetchJSAList = async () => {
  try {
    loading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    let filteredData = mockData
    
    // 根据筛选条件过滤
    if (searchForm.status) {
      filteredData = filteredData.filter(item => item.status === searchForm.status)
    }
    
    if (searchForm.workType) {
      filteredData = filteredData.filter(item => item.workType === searchForm.workType)
    }
    
    // 分页
    const start = (pagination.page - 1) * pagination.size
    const end = start + pagination.size
    
    tableData.value = filteredData.slice(start, end)
    pagination.total = filteredData.length
  } catch (error: any) {
    ElMessage.error(error.message || '获取JSA列表失败')
  } finally {
    loading.value = false
  }
}

// 获取待确认JSA列表
const fetchConfirmJSAList = async () => {
  try {
    confirmLoading.value = true
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 500))
    
    // 只获取待确认状态的JSA
    let filteredData = mockData.filter(item => item.status === 'pending')
    
    // 根据筛选条件过滤
    if (confirmSearchForm.workType) {
      filteredData = filteredData.filter(item => item.workType === confirmSearchForm.workType)
    }
    
    // 分页
    const start = (confirmPagination.page - 1) * confirmPagination.size
    const end = start + confirmPagination.size
    
    confirmTableData.value = filteredData.slice(start, end)
    confirmPagination.total = filteredData.length
  } catch (error: any) {
    ElMessage.error(error.message || '获取待确认JSA列表失败')
  } finally {
    confirmLoading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  fetchJSAList()
}

// 重置
const handleReset = () => {
  searchForm.status = ''
  searchForm.workType = ''
  searchForm.dateRange = []
  pagination.page = 1
  fetchJSAList()
}

// 刷新列表
const refreshList = () => {
  if (activeTab.value === 'list') {
    fetchJSAList()
  } else {
    fetchConfirmJSAList()
  }
  ElMessage.success('刷新成功')
}

// 标签页切换
const handleTabChange = (tabName: string) => {
  if (tabName === 'confirm') {
    fetchConfirmJSAList()
  }
}

// 待确认JSA搜索
const handleConfirmSearch = () => {
  confirmPagination.page = 1
  fetchConfirmJSAList()
}

// 待确认JSA重置
const handleConfirmReset = () => {
  confirmSearchForm.workType = ''
  confirmSearchForm.deadlineRange = []
  confirmPagination.page = 1
  fetchConfirmJSAList()
}

// 跳转到创建页面
const goToCreate = () => {
  router.push('/jsa/create')
}

// 查看详情
const handleView = (row: JSAItem) => {
  // 模拟获取JSA详细数据
  const jsaDetailData = {
    jsaNumber: row.jsaNumber,
    analysisUnit: '安全部',
    jobDescription: row.jobDescription || '高空作业安全分析',
    workPosition: '生产车间',
    workDateDuration: ['2024-01-15', '2024-01-16'] as [string, string],
    personInCharge: '1',
    personsAnalyzedJob: ['1', '2'],
    areaApproval: '3',
    caseSharing: '相关案例分享内容',
    analyzers: ['1', '2', '3'],
    confirmers: ['analyzers', 'responsible_persons'],
    confirmDeadline: row.confirmDeadline,
    analysisData: {
      name: '高空作业JSA分析',
      jobType: '高空作业',
      workSteps: [
        { stepName: '准备工作', responsiblePersons: ['1', '2'] },
        { stepName: '安全防护', responsiblePersons: ['3', '4'] },
        { stepName: '作业执行', responsiblePersons: ['1', '5'] }
      ],
      hazards: [
        { hazardName: '高处坠落' },
        { hazardName: '物体打击' },
        { hazardName: '电气伤害' }
      ],
      controlMeasures: [
        { measureName: '佩戴安全帽' },
        { measureName: '系安全带' },
        { measureName: '设置防护网' }
      ],
      workStepHazards: [
        { workStepSequence: 1, hazardName: '高处坠落' },
        { workStepSequence: 2, hazardName: '物体打击' },
        { workStepSequence: 3, hazardName: '电气伤害' }
      ],
      hazardControls: [
        { hazardName: '高处坠落', controlMeasureName: '系安全带' },
        { hazardName: '物体打击', controlMeasureName: '佩戴安全帽' },
        { hazardName: '电气伤害', controlMeasureName: '设置防护网' }
      ]
    }
  }
  
  selectedJSA.value = jsaDetailData
  detailDialogVisible.value = true
}

// 编辑JSA
const handleEdit = (row: JSAItem) => {
  router.push(`/jsa/edit/${row.id}`)
}

// 确认JSA
const handleConfirm = (row: JSAItem) => {
  router.push(`/jsa/confirm/${row.id}`)
}

// 删除JSA
const handleDelete = async (row: JSAItem) => {
  try {
    await ElMessageBox.confirm(`确定要删除JSA "${row.jsaNumber}" 吗？`, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    ElMessage.success('删除成功')
    fetchJSAList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '删除失败')
    }
  }
}

// 创建作业许可
const handleCreatePermit = (row: JSAItem, permitType: string) => {
  const permitTypeLabel = permitType === 'cold' ? '冷工作业许可' : '热工作业许可'
  ElMessage.info(`正在创建${permitTypeLabel}，关联JSA: ${row.jsaNumber}`)
  
  // 跳转到许可证列表页面，并传递JSA信息
  router.push({
    path: '/permit/list',
    query: {
      jsaId: row.id,
      jsaNumber: row.jsaNumber,
      permitType: permitType
    }
  })
}

// 分页大小变化
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  fetchJSAList()
}

// 当前页变化
const handleCurrentChange = (page: number) => {
  pagination.page = page
  fetchJSAList()
}

// 待确认JSA分页大小变化
const handleConfirmSizeChange = (size: number) => {
  confirmPagination.size = size
  confirmPagination.page = 1
  fetchConfirmJSAList()
}

// 待确认JSA当前页变化
const handleConfirmCurrentChange = (page: number) => {
  confirmPagination.page = page
  fetchConfirmJSAList()
}

// 获取作业类型标签类型
const getWorkTypeTagType = (type: string) => {
  const typeMap: Record<string, string> = {
    high_altitude: 'warning',
    hot_work: 'danger',
    electrical: 'primary',
    confined_space: 'info',
    lifting: 'success'
  }
  return typeMap[type] || 'info'
}

// 获取作业类型标签
const getWorkTypeLabel = (type: string) => {
  const labelMap: Record<string, string> = {
    high_altitude: '高空作业',
    hot_work: '动火作业',
    electrical: '电气作业',
    confined_space: '受限空间',
    lifting: '起重作业'
  }
  return labelMap[type] || type
}

// 获取状态标签类型
const getStatusTagType = (status: string) => {
  const typeMap: Record<string, string> = {
    draft: 'info',
    pending: 'warning',
    confirmed: 'success',
    expired: 'danger'
  }
  return typeMap[status] || 'info'
}

// 获取状态标签
const getStatusLabel = (status: string) => {
  const labelMap: Record<string, string> = {
    draft: '草稿',
    pending: '待确认',
    confirmed: '已确认',
    expired: '已过期'
  }
  return labelMap[status] || status
}

// 获取进度状态
const getProgressStatus = (progress: number) => {
  if (progress >= 100) return 'success'
  if (progress >= 50) return 'warning'
  return 'primary'
}

// 判断是否可以编辑
const canEdit = (status: string) => {
  return ['draft'].includes(status)
}

// 判断是否可以确认
const canConfirm = (status: string) => {
  return ['pending'].includes(status)
}

// 判断是否可以删除
const canDelete = (status: string) => {
  return ['draft', 'expired'].includes(status)
}

// 判断截止时间是否紧急（24小时内）
const isDeadlineUrgent = (deadline: string) => {
  const now = new Date()
  const deadlineDate = new Date(deadline)
  const diffHours = (deadlineDate.getTime() - now.getTime()) / (1000 * 60 * 60)
  return diffHours <= 24 && diffHours > 0
}

onMounted(() => {
  fetchJSAList()
})
</script>

<style lang="scss" scoped>
.jsa-list {
  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;
    
    h2 {
      margin: 0;
      color: #333;
    }
    
    .header-actions {
      display: flex;
      gap: 12px;
    }
  }
  
  .tab-content {
    .filter-card {
      margin-bottom: 20px;
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
  
  .deadline-urgent {
    color: #f56c6c;
    font-weight: bold;
  }
  
  :deep(.el-tabs__content) {
    padding-top: 20px;
  }
}
</style>

